uniform sampler2D texUnit;
uniform mat4 direction;
uniform int isLight;
uniform int isShadows;

vec4 calculate_light(in vec4 vecPoint, in vec3 vecNormal)
{
	vec4 color, diffuse, ambient, specular, ambientGlobal, ecPos, lPos4, lIsec4;
	vec3 aux, normal, lightPos, lightDir, eyePos, eyeDir, halfVector, halfV, viewV, ldir;
	float NdotL, NdotHV, att, dist, pf, fStep;
	bool b;
	
	int nLight;

	ecPos = vecPoint;
	normal = normalize(vec3(vecNormal));

	if (isLight == 1)
	{
		eyePos = vec3(direction * vec4(0.0,0.0,-1.0,1.0));
		eyeDir = normalize(eyePos - vec3(ecPos));
	}
	else
	{
		eyePos = vec3(direction * vec4(0.0,0.0,1.0,1.0));
		eyeDir = normalize(eyePos - vec3(ecPos));
	}

	ambientGlobal = gl_LightModel.ambient * gl_FrontMaterial.ambient;
	color = ambientGlobal;

	for (nLight = 0; nLight < 2; nLight++){
		lPos4 = direction * gl_LightSource[nLight].position;
		lightPos = vec3(lPos4);
		aux = lightPos - vec3(ecPos);
		lightDir = normalize(aux);
		dist = length(aux);

		b = false;

		att = 1.0 / (gl_LightSource[nLight].constantAttenuation +
			gl_LightSource[nLight].linearAttenuation * dist +
			gl_LightSource[nLight].quadraticAttenuation * dist * dist);

		halfVector = normalize(eyeDir + lightDir);

		NdotL = max(dot(normal, lightDir),0.0);
		NdotHV = max(dot(normal, halfVector),0.0);
		
		if (NdotL == 0.0 || NdotHV == 0.0)
			pf = 0.0;
		else
			pf = pow(NdotHV, gl_FrontMaterial.shininess);

		diffuse = gl_LightSource[nLight].diffuse * gl_FrontMaterial.diffuse;
		ambient = gl_LightSource[nLight].ambient * gl_FrontMaterial.ambient;
		specular = gl_FrontMaterial.specular * gl_LightSource[nLight].specular;
		if (!b){
//			color += att * ambient;
			color += att * diffuse * NdotL;
			color += att * specular * pf;
		}
	}
	return color;
}

void main(void)
{
	vec2 texCoord = gl_TexCoord[0].xy;
	vec4 c, pos_tr;
	vec4 pos, dir;
	vec3 norm_tr;

	//bounding box by default
	vec4 bbox_min, bbox_max;
	if (isLight == 1){
		bbox_min = vec4(-1.0,-1.0,-1.0,1.0);
		bbox_max = vec4(1.0,1.0,1.0,1.0);
	}
	else
	{
		bbox_min = vec4(-1.0,-1.0,1.0,1.0);
		bbox_max = vec4(1.0,1.0,-1.0,1.0);
	}

	c = texture2D(texUnit, texCoord);
	gl_FragColor = vec4(c.w, 1.0, 0.0, 1.0);
	if (c.w < 1.0)
	{
		pos = direction * vec4(bbox_min.x + (bbox_max.x - bbox_min.x)*texCoord.x, bbox_min.y + (bbox_max.y - bbox_min.y)*texCoord.y, bbox_min.z, 1.0);
		dir = direction * vec4(bbox_min.x + (bbox_max.x - bbox_min.x)*texCoord.x, bbox_min.y + (bbox_max.y - bbox_min.y)*texCoord.y, bbox_max.z, 1.0);
		pos_tr = pos + c.w*(dir-pos);
		norm_tr = normalize(vec3((c.x*2.0)-1.0, (c.y*2.0)-1.0, (c.z*2.0)-1.0));
		gl_FragColor = calculate_light(pos_tr, norm_tr);
	}
	else
	{
		gl_FragColor = vec4(1.0,1.0,1.0,1.0);
	}
}
